package com.akami.admin;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import xframe.ctl.XDispatchAction;
import xframe.util.CookieUtil;
import xframe.util.UtilMaster;
import xframe.util.db.Row;
import xframe.util.db.Transaction;
import xframe.util.mail.MyAuthenticator;

public class MailAction extends XDispatchAction {
	
	public ActionForward sendMail( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
			Row	req			=	getRequestInfo(request);
			HttpSession session = request.getSession();
	        String host = "smtp.gmail.com";//smtp 서버
	        String subject = UtilMaster.toKor(req.getString("title"));
	        String from = (String)session.getAttribute("s_email"); //보내는 메일
	        String fromName = (String)session.getAttribute("s_name");
	        String to = (String)session.getAttribute("s_email");
	        String content = UtilMaster.toKor(req.getString("contents"));			
			
			
			 try{
		            // 프로퍼티 값 인스턴스 생성과 기본세션(SMTP 서버 호스트 지정)
		            Properties props = new Properties();
		            
		            // G-Mail SMTP 사용시
		            props.put("mail.smtp.starttls.enable","true");
		            props.put("mail.transport.protocol", "smtp");
		            props.put("mail.smtp.host", host);
		            props.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
		            props.put("mail.smtp.port", "465");
		            // props.put("mail.smtp.user", from);
		            props.put("mail.smtp.auth", "true");
		            MyAuthenticator auth = new MyAuthenticator("akami.mail@gmail.com", "ollist1234");
		            Session mailSession = Session.getDefaultInstance(props, auth);
		            Message msg = new MimeMessage(mailSession);
		            msg.setFrom(new InternetAddress(from, MimeUtility.encodeText(fromName,"UTF-8","B")));//보내는 사람 설정
		            InternetAddress[] address = {new InternetAddress(to)};
		            
		            msg.setRecipients(Message.RecipientType.TO, address);//받는 사람설정
		            msg.setSubject(subject);// 제목 설정
		            msg.setSentDate(new java.util.Date());// 보내는 날짜 설정
		            msg.setContent(content,"text/html;charset=euc-kr"); // 내용 설정 (HTML 형식)
		            Transport.send(msg); // 메일 보내기
		            try{
		            	
		    			// 디비연결 시작
		    			Transaction.start(request);		
		    			
		    			String 	listQueryName	=	"newsMaster.publishNewsUpdate";
		    			String	listQuery 		=	mappingQuery(req, listQueryName);	
		    			simpleExecuteUpdate(request, listQuery, listQueryName);
		    			
		    				listQueryName	=	"newsMaster.publishLinkedNewsUpdate";
		    				listQuery 		=	mappingQuery(req, listQueryName);	
		    			simpleExecuteUpdate(request, listQuery, listQueryName);		
		    			
		    			request.setAttribute("nextPage", request.getContextPath()+"/pub.do?command=selectPublishNews");
		    	
		    			//디비연결 종
		    	        Transaction.end(request);
		            
		    		}catch(Exception e){
		    			e.printStackTrace();
		    			Transaction.rollback(request, response);
		    			req.put("system_error", e.toString());
		    			return mapping.findForward( "system_error" );			
		    		}
		            
		            
		            System.out.println("메일 발송을 완료하였습니다.");
		        } catch ( MessagingException ex ) {
					ex.printStackTrace();
					Transaction.rollback(request, response);
					req.put("system_error", ex.toString());
					return mapping.findForward( "system_error" );
		        } catch ( Exception e ) {
					e.printStackTrace();
					Transaction.rollback(request, response);
					req.put("system_error", e.toString());
					return mapping.findForward( "system_error" );
		        }
		        
	
		    		
	return mapping.findForward("sendRedirect");
	}
	
	
	public ActionForward testSendMail( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		Row	req			=	getRequestInfo(request);
		HttpSession session = request.getSession();
		String host = "smtp.gmail.com";//smtp 서버
		String subject = UtilMaster.toKor(req.getString("title"));
		String from = (String)session.getAttribute("s_email"); //보내는 메일
		String fromName = (String)session.getAttribute("s_name");
		String to = (String)session.getAttribute("s_email");
		String content = UtilMaster.toKor(req.getString("contents"));			
		request.setAttribute("nextPage", request.getContextPath()+"/pub.do?command=selectPublishNews");
		
		try{
			// 프로퍼티 값 인스턴스 생성과 기본세션(SMTP 서버 호스트 지정)
			Properties props = new Properties();
			
			// G-Mail SMTP 사용시
			props.put("mail.smtp.starttls.enable","true");
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", host);
			props.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.port", "465");
			// props.put("mail.smtp.user", from);
			props.put("mail.smtp.auth", "true");
			MyAuthenticator auth = new MyAuthenticator("akami.mail@gmail.com", "ollist1234");
			Session mailSession = Session.getDefaultInstance(props, auth);
			Message msg = new MimeMessage(mailSession);
			msg.setFrom(new InternetAddress(from, MimeUtility.encodeText(fromName,"UTF-8","B")));//보내는 사람 설정
			InternetAddress[] address = {new InternetAddress(to)};
			
			msg.setRecipients(Message.RecipientType.TO, address);//받는 사람설정
			msg.setSubject(subject);// 제목 설정
			msg.setSentDate(new java.util.Date());// 보내는 날짜 설정
			msg.setContent(content,"text/html;charset=euc-kr"); // 내용 설정 (HTML 형식)
			Transport.send(msg); // 메일 보내기
			
			System.out.println("메일 발송을 완료하였습니다.");
		} catch ( MessagingException ex ) {
			ex.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", ex.toString());
			return mapping.findForward( "system_error" );
		} catch ( Exception e ) {
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.toString());
			return mapping.findForward( "system_error" );
		}
		
		
		
		return mapping.findForward("sendRedirect");
	}
	
		
	public ActionForward updateCount( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		String cookie	=	"";
		String com =	"dailyFocusPublishNews";
		String id  =	req.getString("publish_idx");
		
		//1.퍼블리싱 날짜가 오늘이 맞는지 확인
		//  오늘이 아니면 조회수를 넣지 않는다.
			cookie	=	CookieUtil.getCookie(request,com+"-"+"id");
			//2.해당 퍼블리싱을 읽었다는 기록이 있는 쿠키가 있는지 확인한다.	
		if(cookie == null){
			//쿠키가 없으면 쿠키를 발급한다.
			CookieUtil.setCookie(response, com+"-"+"id", "id");
		}else if(!req.getString("pub_date").equals(UtilMaster.getToday("yyyy-MM-dd"))){
			return mapping.findForward(null);
		}
		

		

		
		
		
		try{		
		// 디비연결 시작
		Transaction.start(request);		
		
		
		
		String queryName	=	"newsMaster.updateCount";		
		
		//req.get(UtilMaster.convertHtml(req.getString("title")));
		req.put("ip", request.getRemoteAddr());
		
		String	query 	=	mappingQuery(req, queryName);
		String[] preparedIndex = {
				"publish_idx",            
				"ip",            
				"read_index"            
				};
		//PreparedStatement  실행
		preparedExecuteUpdate(request, req, preparedIndex, query);	
		
		queryName	=	"newsMaster.increaseCount";		
		
		query 	=	mappingQuery(req, queryName);
		String[] preparedIndex2 = {
				"publish_idx",            
				"publish_idx"            
				};
		//PreparedStatement  실행
		preparedExecuteUpdate(request, req, preparedIndex2, query);
		

		//디비연결 종
        Transaction.end(request);
												
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
		} 
		
		return mapping.findForward(null);
	}
	
	
	public ActionForward showOpenList( 	ActionMapping       mapping,
			ActionForm          form,
			HttpServletRequest  request,
			HttpServletResponse response ) throws Exception {
		
		Row	req			=	getRequestInfo(request);
		try{		
			// 디비연결 시작
			Transaction.start(request);		
			
			
			String listQueryName	=	"newsMaster.showOpenList";
			String listQuery 		=	mappingQuery(req, listQueryName);	
			simpleExecuteQuery(request, listQuery, listQueryName);					
			
			//디비연결 종
			Transaction.end(request);
			
		}catch(Exception e){
			e.printStackTrace();
			Transaction.rollback(request, response);
			req.put("system_error", e.getMessage());
		} 
		
		return mapping.findForward("showOpenList");
	}
	

}
